package com.valuegroup.smarttodo.ui.programme.ideality;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Ideality;
import com.valuegroup.smarttodo.data.model.Remark;
import com.valuegroup.smarttodo.plugins.icaruseditor.Callback;
import com.valuegroup.smarttodo.plugins.icaruseditor.Icarus;
import com.valuegroup.smarttodo.plugins.icaruseditor.TextViewToolbar;
import com.valuegroup.smarttodo.plugins.icaruseditor.Toolbar;
import com.valuegroup.smarttodo.plugins.icaruseditor.button.Button;
import com.valuegroup.smarttodo.plugins.icaruseditor.button.FontScaleButton;
import com.valuegroup.smarttodo.plugins.icaruseditor.button.TextViewButton;
import com.valuegroup.smarttodo.plugins.icaruseditor.entity.Html;
import com.valuegroup.smarttodo.plugins.icaruseditor.entity.Options;
import com.valuegroup.smarttodo.plugins.icaruseditor.popover.FontScalePopoverImpl;
import com.valuegroup.smarttodo.plugins.icaruseditor.popover.HtmlPopoverImpl;
import com.valuegroup.smarttodo.plugins.icaruseditor.popover.ImagePopoverImpl;
import com.valuegroup.smarttodo.plugins.icaruseditor.popover.LinkPopoverImpl;
import com.valuegroup.smarttodo.plugins.imgsel.ISNav;
import com.valuegroup.smarttodo.plugins.imgsel.config.ISListConfig;
import com.valuegroup.smarttodo.plugins.imgsel.ui.ISListActivity;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.util.AlertUtils;
import com.valuegroup.smarttodo.util.CollectionUtils;
import com.valuegroup.smarttodo.util.Typefaces;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.valuegroup.smarttodo.plugins.icaruseditor.button.Button.NAME_IMAGE;

public class IdealityEditActivity extends BaseActivity {
    @BindView(R.id.button_link)
    TextView buttonLink;
    @BindView(R.id.button_image)
    TextView buttonImage;
    @BindView(R.id.button_font_scale)
    TextView buttonFontScale;
    @BindView(R.id.button_html5)
    TextView buttonHtml5;
    @BindView(R.id.labTitle)
    ClickableTextView labTitle;
    @BindView(R.id.labTitleEdit)
    MultilineEditText labTitleEdit;
    @BindView(R.id.editor)
    WebView editor;

    private Icarus icarus;

    private Long DATA_ID;
    private Ideality DATA;
    private Remark DATA_REMARK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ideality_edit);
        ButterKnife.bind(this);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA = ServiceFactory.getInstance().getIdealityService().getIdealityDao().load(DATA_ID);
        DATA_REMARK = ServiceFactory.getInstance().getRemarkService().getRemark(AppStatus.RemarkType.IDEALITY, DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(this, R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getIdealityService().getDefaultIdeality();
            DATA.setTitle("");
            DATA.setShortTitle("");
        }

        initView();
        initData();
    }

    private void initData() {
        labTitle.setText(DATA.getTitle());


        if (DATA_REMARK != null && !TextUtils.isEmpty(DATA_REMARK.getContent())) {
            icarus.setContent(DATA_REMARK.getContent());
        }
    }

    private void initView() {
        doTitleEditControl();

        TextViewToolbar toolbar = new TextViewToolbar();
        Options options = new Options();
        options.setPlaceholder("描述你的理想...");
        //  img: ['src', 'alt', 'width', 'height', 'data-non-image']
        // a: ['href', 'target']
        options.addAllowedAttributes("img", Arrays.asList("data-type", "data-id", "class", "src", "alt", "width", "height", "data-non-image"));
        options.addAllowedAttributes("iframe", Arrays.asList("data-type", "data-id", "class", "src", "width", "height"));
        options.addAllowedAttributes("a", Arrays.asList("data-type", "data-id", "class", "href", "target", "title"));

        icarus = new Icarus(toolbar, options, editor);
        prepareToolbar(toolbar, icarus);
        icarus.loadCSS("file:///android_asset/editor.css");
       // icarus.loadJs("file:///android_asset/test.js");
        icarus.render();
    }

    private void doTitleEditControl() {
        // 任务主干编辑状态控制
        labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(v.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });


        labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labTitleEdit.setSelection(labTitleEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labTitleEdit, 0);
                } else {
                    // 失去焦点
                    if (labTitleEdit != null && labTitle != null) {
                        labTitle.setText(labTitleEdit.getText());
                        labTitleEdit.setVisibility(View.GONE);
                        labTitle.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }


    @OnClick({R.id.btnBack, R.id.labTitle, R.id.labTitleEdit, R.id.btnSave})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finishAfterTransition();
                break;
            case R.id.btnSave:
                // 保存数据
                if (labTitle.getText().length() == 0) {
                    AlertUtils.showToast(getApplicationContext(), R.string.not_inset_content);
                    return;
                }
                if (DATA.getId() == null && ServiceFactory.getInstance().getIdealityService().existTitle(labTitle.getText().toString())) {
                    AlertUtils.showToast(getApplicationContext(), R.string.exist_content);
                    return;
                }

                DATA.setTitle(labTitle.getText().toString());
                Ideality temp = ServiceFactory.getInstance().getIdealityService().saveIdeality(DATA);
                DATA.setId(temp.getId());
                DATA_ID = temp.getId();

                // 保存富文本信息
                icarus.getContent(new Callback() {
                    @Override
                    public void run(String params) {
                        if (!TextUtils.isEmpty(params)) {
                            System.out.println("富文本内容：" + params);
                            Html html = JSON.parseObject(params, Html.class);
                            DATA_REMARK = ServiceFactory.getInstance().getRemarkService().saveRemark(AppStatus.RemarkType.IDEALITY, DATA_ID, html.getContent());
                        }
                    }
                });


                Intent intent = new Intent(this, IdealityActivity.class);
                intent.putExtra(IdealityActivity.PARAMS_KEY, DATA_ID);
                startActivityForResult(intent, 1003);

                break;
            case R.id.labTitle:
                labTitle.setVisibility(View.GONE);

                labTitleEdit.setText(labTitle.getText());
                labTitleEdit.setVisibility(View.VISIBLE);

                // 获得焦点
                labTitleEdit.setFocusable(true);
                labTitleEdit.setFocusableInTouchMode(true);
                labTitleEdit.requestFocus();

                break;
        }
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }


    private static final int REQ_CAMERA_PERMISSION = 59;

    private Toolbar prepareToolbar(TextViewToolbar toolbar, Icarus icarus) {
        Typeface iconfont = Typefaces.getSimditor(this);
        HashMap<String, Integer> generalButtons = new HashMap<>();
        generalButtons.put(Button.NAME_BOLD, R.id.button_bold);
        generalButtons.put(Button.NAME_OL, R.id.button_list_ol);
        generalButtons.put(Button.NAME_BLOCKQUOTE, R.id.button_blockquote);
        generalButtons.put(Button.NAME_HR, R.id.button_hr);
        generalButtons.put(Button.NAME_UL, R.id.button_list_ul);
        generalButtons.put(Button.NAME_ALIGN_LEFT, R.id.button_align_left);
        generalButtons.put(Button.NAME_ALIGN_CENTER, R.id.button_align_center);
        generalButtons.put(Button.NAME_ALIGN_RIGHT, R.id.button_align_right);
        generalButtons.put(Button.NAME_ITALIC, R.id.button_italic);
        generalButtons.put(Button.NAME_INDENT, R.id.button_indent);
        generalButtons.put(Button.NAME_OUTDENT, R.id.button_outdent);
        generalButtons.put(Button.NAME_CODE, R.id.button_math);
        generalButtons.put(Button.NAME_UNDERLINE, R.id.button_underline);
        generalButtons.put(Button.NAME_STRIKETHROUGH, R.id.button_strike_through);

        for (String name : generalButtons.keySet()) {
            TextView textView = findViewById(generalButtons.get(name));
            if (textView == null) {
                continue;
            }
            textView.setTypeface(iconfont);
            TextViewButton button = new TextViewButton(textView, icarus);
            button.setName(name);
            toolbar.addButton(button);
        }
        buttonLink.setTypeface(iconfont);
        TextViewButton linkButton = new TextViewButton(buttonLink, icarus);
        linkButton.setName(Button.NAME_LINK);
        linkButton.setPopover(new LinkPopoverImpl(buttonLink, icarus));
        toolbar.addButton(linkButton);

        buttonImage.setTypeface(iconfont);
        TextViewButton imageButton = new TextViewButton(buttonImage, icarus);
        imageButton.setName(NAME_IMAGE);
        imageButton.setPopover(new ImagePopoverImpl(buttonImage, icarus));
        toolbar.addButton(imageButton);
        buttonImage.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(v.getContext(), Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA},
                            REQ_CAMERA_PERMISSION);
                    return;
                }

                openImageSelector(true);
            }
        });

        buttonHtml5.setTypeface(iconfont);
        TextViewButton htmlButton = new TextViewButton(buttonHtml5, icarus);
        htmlButton.setName(Button.NAME_HTML);
        htmlButton.setPopover(new HtmlPopoverImpl(buttonHtml5, icarus));
        toolbar.addButton(htmlButton);

        buttonFontScale.setTypeface(iconfont);
        TextViewButton fontScaleButton = new FontScaleButton(buttonFontScale, icarus);
        fontScaleButton.setPopover(new FontScalePopoverImpl(buttonFontScale, icarus));
        toolbar.addButton(fontScaleButton);
        return toolbar;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_CAMERA_PERMISSION) {
            boolean cameraGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
            openImageSelector(cameraGranted);
        }
    }

    protected static final int REQ_SELECT_IMAGE = 879;

    private void openImageSelector(boolean supportSelfie) {
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(R.drawable.ic_back)
                // 标题
                //.title(getString(R.string.webview_select_picture))
                .title("选择图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#3F51B5"))
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(supportSelfie)
                // 最大选择图片数量，默认9
                .maxNum(9)
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQ_SELECT_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 图片选择结果回调
        if (requestCode == REQ_SELECT_IMAGE
                && resultCode == Activity.RESULT_OK
                && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);
            if (CollectionUtils.isNotEmpty(pathList)) {
                String path = pathList.get(0);
                System.out.println("path" + path);
                //create ImageObject
                // Uri imageUri = mListener.createImage(path);
                //insert to note
                // mEditor.insertImage("untitled", imageUri.toString());

                Uri u = new Uri.Builder().scheme("file").path("//" + path).build();
                //System.out.println(">>>>>>>>>>>>>>>>>>>>>> paramsString:" + u.toString());

                // 创建根目录
                File rootDir = new File(Environment.getExternalStorageDirectory(), "SmartTodo" + File.separator + "img" + File.separator + "idealityContent");
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }

                // 指定输出文件
                File cropImageFile = new File(rootDir, System.currentTimeMillis() + ".jpg");
                //File cropImageFile = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg");

                // 图片裁剪
                CropImage.activity(u)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setActivityTitle("图片裁剪")
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        .setCropMenuCropButtonTitle("Done")
                        .setOutputUri(Uri.fromFile(cropImageFile))
                        .start(this);

            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                icarus.jsExec("javascript: editor.toolbar.execCommand('" + NAME_IMAGE + "','" + result.getUri().toString() + "')");

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    protected void onDestroy() {
        editor.destroy();
        super.onDestroy();
    }
}
